package org.epidroid.epidroid.chronos.engine;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.epidroid.epidroid.chronos.engine.exceptions.ChronosException;
import org.epidroid.epidroid.chronos.engine.objects.ChronosCalendar;
import org.epidroid.epidroid.chronos.engine.objects.ChronosNode;
import org.epidroid.epidroid.chronos.engine.objects.ChronosWeek;
import org.epidroid.epidroid.chronos.engine.parsers.CalendarParser;
import org.epidroid.epidroid.chronos.engine.parsers.MenuParser;

import android.util.Log;

public class Chronos {

	public static final String LOGCAT = "chronos";

	private static String HOST = "http://webservices.chronos.epita.net";

	public String performQuery(String query) {
		BufferedReader in = null;
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet();
			request.setURI(new URI(HOST + query));
			HttpResponse response = client.execute(request);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			String page = sb.toString();
			return page;
		} catch (Exception e) {
			Log.e(Chronos.LOGCAT, e.getMessage());
			return null;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					Log.e(Chronos.LOGCAT, e.getMessage());
					return null;
				}
			}
		}
	}

	public ChronosNode getMenu(String name) {
		String query = "/GetWeeks.aspx?getMenu=" + name;
		String xmlContent = performQuery(query);
		ChronosNode node = MenuParser.parse(xmlContent, name);
		return node;
	}

	public ChronosWeek getWeek(int week, String group) throws ChronosException {
		ChronosCalendar c = getWeeks(week, group, 1);
		if ((null == c) || (c.getWeeks().size() == 0))
			throw new ChronosException("Could not retrieve week");
		ChronosWeek w = c.getWeeks().get(0);

		return w;
	}

	public ChronosCalendar getWeeks(int week, String group, int num)
			throws ChronosException {

		String query = "/GetWeeks.aspx?week=" + week + "&group=" + group
				+ "&num=" + num;
		String xmlContent = performQuery(query);
		ChronosCalendar calendar = CalendarParser.parse(xmlContent);
		return calendar;
	}
}
